package com.zmn.oms.services.impl.comment;

import com.google.common.collect.Lists;
import com.zmn.comment.common.dro.cmt.CommentChannelDRO;
import com.zmn.comment.common.dro.cmt.CommentDetailDRO;
import com.zmn.comment.dubbo.interfaces.cmt.CmtCommentListRemoteService;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.model.entity.comment.OrderComment;
import com.zmn.oms.model.entity.comment.OrderCommentDetail;
import com.zmn.oms.model.entity.remark.OrderRemark;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.persistence.interfaces.comment.OrderCommentDao;
import com.zmn.oms.services.interfaces.comment.OrderCommentService;
import com.zmn.oms.services.interfaces.remark.OrderRemarkService;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 类描述：
 *
 * @author lujia
 * @date 2018/11/28 15:33
 */
@Slf4j
@Service
public class OrderCommentServiceImpl implements OrderCommentService {

    @Autowired(required = false)
    private OrderCommentDao orderCommentDao;
    @Autowired
    private OrderWorkService orderWorkService;
    @Autowired
    private OrderRemarkService orderRemarkService;

    @Reference(version = com.zmn.comment.dubbo.interfaces.utils.DubboConsts.INTERFACE_VERSION, check = false,timeout = 100000)
    private CmtCommentListRemoteService cmtCommentListRemoteService;

    @Override
    public OrderComment findCommentByKey(Long orderId) {
        // log.info("cmtCommentListRemoteService.getOrderCommentByOrderId params={}", orderId);
        ResponseDTO<CommentDetailDRO> orderCommentDro = cmtCommentListRemoteService.getCommentByOrderId(orderId);
        // log.info("cmtCommentListRemoteService.getOrderCommentByOrderId result={}", orderCommentDro);
        if (!orderCommentDro.isSuccess() || Objects.isNull(orderCommentDro.getData())) {
//            return orderCommentDao.findCommentByKeyAndType(orderId, OrderConsts.COMMENT_TYPE_DEFAULT);
            return null;
        }
        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId, orderId);
        OrderRemark orderRemark = orderRemarkService.findByOrderIdAndType(orderId, orderWork.getWorkId(), OrderConsts.ORDER_REMARK_TYPE_REPLY);
        return getOrderComment(orderCommentDro.getData(), orderWork, orderRemark);
    }

    @Override
    public List<OrderComment> findChannelCommentListByKey(Long orderId) {
        log.info("cmtCommentListRemoteService.listCommentByOrderId params={}", orderId);
        ResponseDTO<List<CommentChannelDRO>> orderCommentDro = null;
        try {
            orderCommentDro = cmtCommentListRemoteService.listCommentByOrderId(orderId);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        log.info("cmtCommentListRemoteService.listCommentByOrderId result={}", orderCommentDro);
        if (!orderCommentDro.isSuccess() || Objects.isNull(orderCommentDro.getData())) {
            return null;
        }
        List<OrderComment> orderCommentList = Lists.newArrayList();
        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId, orderId);
        OrderRemark orderRemark = orderRemarkService.findByOrderIdAndType(orderId, orderWork.getWorkId(), OrderConsts.ORDER_REMARK_TYPE_REPLY);
        orderCommentDro.getData().forEach(orderComment -> {
            CommentDetailDRO commentDetailDRO = BeanMapper.map(orderComment, CommentDetailDRO.class);
            orderCommentList.add(getOrderComment(commentDetailDRO, orderWork, orderRemark));
        });
        return orderCommentList;
    }

    private OrderComment getOrderComment(CommentDetailDRO orderComment, OrderWork orderWork, OrderRemark remark) {
        OrderComment comment = new OrderComment();
        comment.setCommentId(orderWork.getOrderId());
        comment.setUserId(orderComment.getOperatorId());
        if (Objects.nonNull(orderComment.getOrder())) {
            comment.setMasterId(orderComment.getOrder().getEngineerId());
        }
        comment.setType(orderComment.getCommentType());
        comment.setScore(orderComment.getScore());
        comment.setContent(orderComment.getContent());
        comment.setAppendContent(orderComment.getAppendContent());
        comment.setStatus(GlobalConsts.YES);
        comment.setCreater(orderComment.getCreater());
        comment.setCreateTime(DateUtil.parse(orderComment.getCommentTime()));
        comment.setAppendTime(DateUtil.parse(orderComment.getAppendTime()));
        if (Objects.nonNull(orderComment.getStore())) {
            comment.setStoreName(orderComment.getStore().getStoreName());
        }
        if (CollectionUtil.isNotNullOrEmpty(orderComment.getCommentLabelList())) {
            List<OrderCommentDetail> collect = orderComment.getCommentLabelList()
                    .stream()
                    .map(e -> {
                        OrderCommentDetail detail = new OrderCommentDetail();
                        detail.setMapId(e.getLabelId());
                        detail.setMapName(e.getLabelName());
                        return detail;
                    }).collect(Collectors.toList());
            comment.setDetailList(collect);
        }else {
            comment.setDetailList(Lists.newArrayList());
        }
        comment.setReplyVisiterId(orderWork.getReplyVisiterId());
        comment.setReplyTime(orderWork.getReplyVisitTime());
        if (Objects.nonNull(remark)) {
            comment.setReplyContent(remark.getContent());
        }
        return comment;
    }

    @Override
    public List<OrderComment> listOrderCommentByOrderIdList(List<Long> orderIdList) {
        if (CollectionUtil.isNullOrEmpty(orderIdList)) {
            return Lists.newArrayList();
        }
        ResponseDTO<List<CommentDetailDRO>> commentListDro = cmtCommentListRemoteService.listCommentSimpleByOrderIdList(orderIdList);
        if (!commentListDro.isSuccess() || CollectionUtil.isNullOrEmpty(commentListDro.getData())) {
            List<OrderComment> orderComments = orderCommentDao.listOrderCommentByOrderIdListAndType(orderIdList, OrderConsts.COMMENT_TYPE_DEFAULT);
            return Optional.ofNullable(orderComments).orElse(Lists.newArrayList());
        }

        // 去重，优先取用户评价信息
        Map<Long, CommentDetailDRO> commentDetailDROMap = new HashMap<>();
        for (CommentDetailDRO commentDetailDRO : commentListDro.getData()) {
            CommentDetailDRO comment = commentDetailDROMap.get(commentDetailDRO.getCommentObjectId());
            if (Objects.isNull(comment) || !Objects.equals(comment.getCommentType(), OrderConsts.COMMENT_TYPE_USER)) {
                comment = commentDetailDRO;
                commentDetailDROMap.put(comment.getCommentObjectId(), comment);
            }
        }
        Collection<CommentDetailDRO> values = commentDetailDROMap.values();

        List<OrderComment> orderComments = new ArrayList<>();
        // 评论系统内没用，则查询本地历史数据
//        List<Long> commentDROIds = values.stream().map(CommentDetailDRO::getCommentObjectId).collect(Collectors.toList());
//        List<Long> copyOrderIdList = Lists.newArrayList(orderIdList);
//        copyOrderIdList.removeAll(commentDROIds);
//        if (CollectionUtil.isNotNullOrEmpty(copyOrderIdList)) {
//            List<OrderComment> orderCommentList = orderCommentDao.listOrderCommentByOrderIdListAndType(copyOrderIdList, OrderConsts.COMMENT_TYPE_DEFAULT);
//            if (CollectionUtil.isNotNullOrEmpty(orderCommentList)) {
//                orderComments.addAll(orderCommentList);
//            }
//        }
        List<OrderWork> orderWorks = orderWorkService.listEsOrderWorkByOrderIdList(orderIdList);
        Map<Long, OrderWork> orderWorkMap = orderWorks.stream().collect(Collectors.toMap(OrderWork::getWorkId, orderWork -> orderWork));
        List<OrderRemark> orderRemarks = orderRemarkService.listOrderRemarkByOrderIdListAndType(orderIdList, OrderConsts.ORDER_REMARK_TYPE_REPLY);
        Map<Long, OrderRemark> remarkMap = new HashMap<>();
        if (CollectionUtil.isNotNullOrEmpty(orderRemarks)) {
            remarkMap = orderRemarks.stream().collect(Collectors.toMap(OrderRemark::getWorkId, orderRemark -> orderRemark));
        }
        for (CommentDetailDRO commentDro : values) {
            orderComments.add(getOrderComment(commentDro, orderWorkMap.get(commentDro.getCommentObjectId()), remarkMap.get(commentDro.getCommentObjectId())));
        }

        return orderComments;
    }
}
